package com.hqyj.service.impl;


import com.hqyj.dao.ManagerDao;
import com.hqyj.pojo.Admin;
import com.hqyj.pojo.Manager;

import com.hqyj.service.managerService;
import com.hqyj.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class managerServiceImpl implements managerService {



    @Autowired
    private ManagerDao managerDao;


//   @Override
//    public Manager login(String username, String password) {
//        Manager manager =managerDao.findManagerByUserName(username,password);
//       return manager;
//    }
@Override
public Manager getOneByUsername(String username) {
    return managerDao.queryByUsername(username);
}

    //使用shiro框架来实现登录
    @Override
    public Map<String, Object> login(String username, String password) {
        Map<String, Object> result = new HashMap<>();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //判断当前是否已经认证过
        if(!subject.isAuthenticated()){
            //创建一个认证令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            //做登录
            try{
                subject.login(token);
            }catch (UnknownAccountException e){
                //未知账号异常
                result.put("code", -1);
                result.put("message",username+"用户不存在");
                return result;
            }catch (IncorrectCredentialsException e){
                //密码错误异常
                result.put("code", -2);
                result.put("message",username+"用户密码错误");
                return result;
            }catch (AuthenticationException e){
                result.put("code",-10);
                result.put("message","认证失败");
                return result;
            }
        }
        //认证通过，获取已保存在shiro session域中的用户信息
        Session session = subject.getSession();
        Object loginUser = session.getAttribute("loginUser");
        result.put("code", 1);
        result.put("message",username +"认证成功");
        //直接返回给控制器方法
        result.put("loginUser",loginUser);
        System.out.println(result.toString());
        return result;
    }

    @Override
    public Map<String, Object> logout() {
        //使用shiro框架获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //使用shiro对当前用户登出
        subject.logout();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("message", "成功登出");
        return result;
    }

}


